package com.dcits.business.server;

import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.dcits.business.userconfig.UserSpace;
import com.dcits.constant.ConstantReturnCode;
import com.dcits.mvc.base.BaseController;
import com.dcits.tool.StringUtils;
import com.dcits.tool.ThreadPoolUtil;

/**
 * 通用类型控制器<br>
 * 新增加的监控类型需要继承此类
 * @author xuwangcheng
 * @version 2018.3.21
 *
 */
public abstract class BaseServerController extends BaseController {
	/**
	 * 获取当前类型监控的所有服务器信息
	 */
	public void list() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		String serverType = getPara("serverType");
		
		List<ViewServerInfo> infos = space.getServers().get(serverType);
		for (final ViewServerInfo info:infos) {
			//info.setInfo();
			ThreadPoolUtil.execThread(new Runnable() {				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					info.getMonitoringInfo();					
				}
			});
		}
		renderSuccess(JSONObject.toJSON(infos), "获取信息成功!");	
	};
	/**
	 * 从当前监控列表中删除指定服务器
	 */
	public void del() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		ViewServerInfo server = space.getServerInfo(getPara("serverType"), getParaToInt("viewId"));
		server.disconect();
		space.delServerInfo(getPara("serverType"), getParaToInt("viewId"));
		renderSuccess(null, "删除成功!");
	};
	/**
	 * 重新连接
	 */
	public void reconnect() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		ViewServerInfo info = space.getServerInfo(getPara("serverType"), getParaToInt("viewId"));
		info.disconect();
		String flag = info.connect();
		
		if ("true".equalsIgnoreCase(flag)) {
			renderSuccess(null, "重连成功!");
		} else {
			renderError(ConstantReturnCode.SERVER_CONNECT_FAILED, flag);
		}	
	};
	
	/**
	 * 删除某种类型的全部
	 */
	public void delAll() {
		UserSpace space = UserSpace.getUserSpace(getPara("userKey"));
		String serverType = getPara("serverType");
		if (StringUtils.isEmpty(serverType)) {
			renderError(ConstantReturnCode.VALIDATE_FAIL, "没有serverType参数!");
			return;
		}
		
		space.getServers().get(serverType).clear();
		renderSuccess(null, "删除成功!");
		//System.gc();
	}
}
